package main_com.Controlers.login;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import main_com.mapper.UserMapper;
import main_com.pojo.LoginBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Administrator
 */
@Controller
@RequestMapping("/LoginController")
public class LoginController {

    @Autowired
    UserMapper userMapper;

    @RequestMapping("/login")
    @ResponseBody
    protected Map<String, String> login(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Map<String, String> errorMap = new HashMap<>();
        String userName = request.getParameter("userName");
        String password = request.getParameter("password");
        LoginBean loginBean = new LoginBean(userName, password);
        if (userName.isEmpty()) {
            errorMap.put("userNameError", "用户名不能为空");
            return errorMap;
        } else if (password.isEmpty()) {
            errorMap.put("passwordError", "密码不能为空");
            return errorMap;
        } else {
            try {
                if (userMapper.findUserName(userName) <= 0) {
                    errorMap.put("userNameError", "用户名不存在");
                    return errorMap;
                }
                if (userMapper.findLoginBean(loginBean) <= 0) {
                    errorMap.put("passwordError", "密码错误");
                    return errorMap;
                }
                HttpSession session = request.getSession();//获取session对象
                ArrayList login = new ArrayList();//实例化列表对象
                login.add(loginBean);//把个人信息保存到列表中
                session.setAttribute("login", login);//把列表保存到session对象中，以便在别的页面中获取个人信息
                request.getServletContext().setAttribute("userName", userName);
                return new HashMap<>(); // 无错误时返回空的Map
            } catch (Exception e) {
                e.printStackTrace();
                errorMap.put("error", "系统异常，请稍后再试");
                return errorMap;
            }
        }
    }
}